#include "Map.h"
#include "ui_Map.h"
#include <QTimer>
#include <QDebug>
#include<QPropertyAnimation>


Map::Map(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Map)
    , scene(new QGraphicsScene(this))
    , character(nullptr)
    , mapBackground(nullptr)//陆珊瑚对象
    ,lushanhu1(nullptr)//一等小屋对象
    ,tedeng1(nullptr)//特等下午对象
    // , longjiejing1(nullptr)//龙结晶对象
    , yideng1(nullptr)
{
    ui->setupUi(this);
    // 初始化图形视图
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // 窗口大小（物理像素）
    this->setFixedSize(1200, 760);  // 1800/1.5, 1140/1.5 和缩放抵消

    setWindowTitle("我的艾露猫");
    // graphicsView 大小（逻辑像素，与窗口一致）
    ui->graphicsView->setFixedSize(1200, 760);

    // 设置场景大小（逻辑像素，与背景图一致）
    scene->setSceneRect(0, 0, 1800, 1140);

    // 调整 graphicsView 的变换矩阵，使 1800x1140 的场景适配 1200x760 的视图
    ui->graphicsView->setTransform(QTransform::fromScale(1200.0/1800.0, 760.0/1140.0));

    //陆珊瑚的返回地图
    connect(lushanhu1,&Lushanhu::backToMap,[this](){
        this->show();
    });

    //龙结晶的返回地图

    //一等小屋的返回地图



    // 设置地图和角色
    setupMap();
    setupCharacter();
    setupLocations();

    //移动定时器
    startTimer(16);
}

Map::~Map()
{
    delete ui;
    if(lushanhu1) delete lushanhu1;//释放内存
    if(tedeng1) delete tedeng1;
    if(yideng1) delete yideng1;
}

//地图图片
void Map::setupMap()
{
    // 加载地图背景
    mapBackground = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/map.PNG"));
    scene->addItem(mapBackground);
    mapBackground->setPos(0, 0);  // 明确设置位置
    mapBackground->setZValue(-1); // 确保背景在最底层
    scene->setSceneRect(mapBackground->boundingRect());

}

//角色图片
void Map::setupCharacter()
{

    charAnimations();
    // 加载角色图片
   character = new QGraphicsPixmapItem();
    character->setPos(scene->width()/2, scene->height()/2); // 初始位置居中
    character->setTransformOriginPoint(character->boundingRect().center());
    character->setPixmap(animationFrames[Down][0]);
    character->setZValue(10);//最上方


    scene->addItem(character);

}

//互动区域
void Map::setupLocations()
{
    // 定义可交互区域 (根据实际地图调整)
    this->lushanhu = QRect(1050,100,300,200);
    // this->ljj=QRect();//龙结晶
    this->yd=QRect(700,700,500,400);//一等小屋
    this->td=QRect(100,700,500,400);//特等小屋



    // // 可视化区域边界调试用
    // QGraphicsRectItem *bRect = new QGraphicsRectItem(yd);
    // bRect->setPen(QPen(Qt::green));
    // scene->addItem(bRect);
}

//移动控制
void Map::keyPressEvent(QKeyEvent *event)
{
    switch(event->key()) {
    case Qt::Key_W: moveUp = true;  currentDirection =Down;break;
    case Qt::Key_S: moveDown = true;  currentDirection = Down; break;
    case Qt::Key_A: moveLeft = true;  currentDirection = Left; break;
    case Qt::Key_D: moveRight = true;  currentDirection = Right ;break;
    case Qt::Key_F: checkPositionAndInteract(); break;
    }
}

//释放键盘
void Map::keyReleaseEvent(QKeyEvent *event)
{
    switch(event->key()) {
    case Qt::Key_W: moveUp = false; break;
    case Qt::Key_S: moveDown = false; break;
    case Qt::Key_A: moveLeft = false; break;
    case Qt::Key_D: moveRight = false; break;
    }
}


void Map::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event);

    // 计算新位置
    QPointF newPos = character->pos();
    if(moveUp) newPos.ry() -= moveSpeed;
    if(moveDown) newPos.ry() += moveSpeed;
    if(moveLeft) newPos.rx() -= moveSpeed;
    if(moveRight) newPos.rx() += moveSpeed;

    //边界检查
    QRectF charRect(newPos, character->boundingRect().size());
    QRectF sceneRect = scene->sceneRect();

    if(charRect.left() < sceneRect.left()) newPos.setX(sceneRect.left());
    if(charRect.right() > sceneRect.right()) newPos.setX(sceneRect.right() - charRect.width());
    if(charRect.top() < sceneRect.top()) newPos.setY(sceneRect.top());
    if(charRect.bottom() > sceneRect.bottom()) newPos.setY(sceneRect.bottom() - charRect.height());

    QPointF center = charRect.center();

    if(lushanhu.contains(center.toPoint())) {
        ui->interHint->setText("按F键进入陆珊瑚");
        ui->interHint->move(800,100);
        ui->interHint->show();
    }
    // //龙结晶
    // else if(ljj.contains(center.toPoint())){

    // }
    // 一等
    else if(yd.contains(center.toPoint())){
        ui->interHint->setText("按F键进入一等小屋");
        ui->interHint->move(500,450);//假坐标
        ui->interHint->show();
    }
    //特等
    else if(td.contains(center.toPoint())){
        ui->interHint->setText("按F键进入特等小屋");
        ui->interHint->move(200,450);//假坐标
        ui->interHint->show();
        }
    else {
        ui->interHint->hide();
    }
    // 更新位置
    character->setPos(newPos);
}

//检查交互函数
void Map::checkPositionAndInteract()
{
    QRectF charRect(character->pos(), character->boundingRect().size());
    QPointF center = charRect.center();
    //陆珊瑚进入
    if(lushanhu.contains(center.toPoint())) {
        this->hide();
        enterLocation(1);
    }



    // else if(ljj.contains(center.toPoint())) {
    //     enterLocation(2); //
    // }
    else if(yd.contains(center.toPoint())) {
        enterLocation(3); //
    }
    else if(td.contains(center.toPoint())) {
        enterLocation(4);
    }

}

void Map::enterLocation(int location)
{
    switch(location) {
    case 1: // 陆珊瑚
        if(!lushanhu1) {
            lushanhu1 = new Lushanhu();//不要父亲，避免被隐藏
            connect(lushanhu1, &Lushanhu::backToMap, this, &Map::show);
        }
        else{
            lushanhu1->Lushanhu::restartGame();
        }

        lushanhu1->show();

        break;

    // case 2: //
    //     if(!longjiejing1) {
    //         longjiejing1= new longjiejing();
    //         connect(longjiejing1, &longjiejing::backToMap, this, &Map::show);
    //     }
    //     longjiejing1->show();
    //     break;

    case 3: //
        if(!yideng1) {
            yideng1 = new yideng();
            // connect(yideng1, &yideng::backToMap, this, &Map::show);
        }
        yideng1->show();
        break;
    case 4:
        if(!tedeng1) {
            tedeng1 = new tedeng();//不要父亲，避免被隐藏
            // connect(tedeng1, &tedeng::backToMap, this, &Map::show);
        }
        // else{
        //     tedeng1->tedeng::restartGame();
        // }

        tedeng1->show();

        break;
    }
}

void Map::charAnimations()
{
    // 加载各方向动画帧
    animationFrames[Down] = {
        QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/zheng1.png"),
        QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/zheng2.png")
    };

    animationFrames[Left] = {
        QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/zuo1.png"),
        QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/zuo2.png")
    };

    animationFrames[Right] = {
        QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/you1.png"),
        QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/you2.png")
    };

    // 设置动画定时器
    animationTimer = new QTimer(this);
    connect(animationTimer, &QTimer::timeout, this, &Map::updateAnimation);
    animationTimer->start(100); // 每100毫秒更新一帧
}

//小小动画做的我好累
void Map::updateAnimation()
{
    if(moveUp||moveDown || moveLeft || moveRight) {
        currentFrame = (currentFrame + 1) % animationFrames[currentDirection].size();
        character->setPixmap(animationFrames[currentDirection][currentFrame]);
    }
    else {
        // 站立时显示第一帧
        character->setPixmap(animationFrames[currentDirection][0]);
    }
}


